package com.my.socket.nio.v24;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

/**
 * Created by ZhongGang
 * at 2018/7/4 17:03
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private Selector acceptSelector;
    private Selector[] readSelectors = new Selector[2];
    private Selector[] writeSelectors = new Selector[2];
    private ServerSocketChannel serverSocketChannel;

    public Server(String host, int port) throws Exception {
        this.acceptSelector = Selector.open();
        for (int i = 0; i < this.readSelectors.length; i++) {
            this.readSelectors[i] = Selector.open();
        }
        for (int i = 0; i < this.writeSelectors.length; i++) {
            this.writeSelectors[i] = Selector.open();
        }

        this.serverSocketChannel = ServerSocketChannel.open();
        this.serverSocketChannel.configureBlocking(false);
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        this.serverSocketChannel.bind(inetSocketAddress);
        this.serverSocketChannel.register(this.acceptSelector, SelectionKey.OP_ACCEPT);
    }

    public void startup() throws Exception {
        new Thread(new AcceptTask(this.acceptSelector, this.readSelectors), "accept-task").start();
        for (int i = 0; i < readSelectors.length; i++) {
            Selector readSelector = readSelectors[i];
            new Thread(new ReadTask(readSelector, this.writeSelectors), "read-task-" + i).start();
        }

        for (int i = 0; i < writeSelectors.length; i++) {
            Selector writeSelector = writeSelectors[i];
            new Thread(new WriteTask(writeSelector), "write-task-" + i).start();
        }
    }

    public static void main(String[] args) throws Exception {
        String host = "127.0.0.1";
        int port = 9999;
        Server server = new Server(host, port);
        server.startup();
        LOGGER.info("listen at {}:{}", host, port);
    }
}
